package com.mxdx.edu.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import com.mxdx.edu.common.CommonUtils;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.springframework.stereotype.Service;

import com.mxdx.edu.common.DateFormatUtils;
import com.mxdx.edu.common.DateStyle;
import com.mxdx.edu.service.ISerialService;
import com.mxdx.edu.util.StringUtils;

/**
 * 获取序号服务实现类
 * 
 * @author guoxc
 * 
 */
@Service
public class SerialService implements ISerialService {

	@Resource
	private MySQLMaxValueIncrementer mySQLMaxValueIncrementer;

	@Override
	public String getOrderId(String orderType) {
		StringBuilder sb = new StringBuilder();
		if (orderType.length() == 1) {
			sb.append("0");
		} else if (orderType.length() == 0) {
			orderType = "00";
		}
		sb.append(orderType);
		String dateStr = DateFormatUtils.DateToString(new Date(),
				DateStyle.YYYYMMDDHHMMSS);
		sb.append(dateStr);
		/* 自动生成主键 */
		Long value = mySQLMaxValueIncrementer.nextLongValue();
		String numStr = String.valueOf(value);
		int len = numStr.length();
		if (numStr.length() <= 5) {
			numStr = StringUtils.alignRight(numStr, 5, '0');
		} else {
			numStr = numStr.substring(len - 5, len);
		}

		sb.append(numStr);
		return sb.toString();
	}

	public String generateSerialNum(String type, int size) {
		StringBuilder sb = new StringBuilder();
		sb.append(type);
		String gerStr = String.valueOf(mySQLMaxValueIncrementer.nextIntValue());
		int len = gerStr.length();
		sb.append(len).append(gerStr);
		int nowSize = sb.length();
		if(nowSize > size) {
			return sb.substring(nowSize-size);
		}
		if(nowSize == size) {
			return sb.toString();
		}
		return sb.append(CommonUtils.generateCode(size - nowSize)).toString();
	}



}
